package com.hewei.controller;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hewei.domain.Girl;
import com.hewei.domain.Result;
import com.hewei.repository.GirlRepository;
import com.hewei.service.GirlService;
import com.hewei.utils.ResultUtil;

@RestController
public class GirlController {
	private final static Logger logger = LoggerFactory.getLogger(GirlController.class);
	
	@Autowired
	private GirlRepository girlRepository;
	
	@Autowired
	private GirlService girlService;
	
	@GetMapping(value = "/girls")
	public List<Girl> query() {
		logger.info("查询所有女生");
		//1、单条件排序 适合对单一属性做排序
		Sort sort = new Sort(Sort.Direction.DESC,"id");
		//2、多条件组合排序 适合对多个属性，采取同一种排序方式的排序
		//List<String> sortProperties = new ArrayList<String>();
		//sortProperties.add("id");
		//sortProperties.add("age");
		//Sort sort = new Sort(Sort.Direction.DESC,sortProperties);
		//girlRepository.findAll(sort);
		//3、通过创建Sort.Order对象的集合创建sort对象 适合所有情况，比较容易设置排序方式
//		List<Sort.Order> orders = new ArrayList<Sort.Order>();
//		orders.add(new Sort.Order(Sort.Direction.DESC,"id"));
//		orders.add(new Sort.Order(Sort.Direction.ASC,"age"));
//		return girlRepository.findAll(new Sort(orders));
		return girlRepository.findAll(sort);
	}
	
	@PostMapping(value = "/girlid")
	public Girl queryById(@RequestParam("id")Integer id) {
		return girlRepository.findOne(id);
	}
	
	@PostMapping(value = "/save")
	public Result<Girl> save(@Valid Girl girl, BindingResult bindingResult) {
		if(bindingResult.hasErrors()) {
			return ResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage());
		}
		return ResultUtil.success(girlRepository.save(girl));
	}
	
	@PostMapping(value = "/delete")
	public void delete(@RequestParam("id")Integer id) {
		girlRepository.delete(id);
	}
	
	@PostMapping(value = "/girls/two")
	public void girlTwo() {
		girlService.insertTwo();
	}
	
	@PostMapping(value = "girls/getAge")
	public void getAge(@RequestParam("id") Integer id) throws Exception {
		girlService.getAge(id);
	}
}
